package com.solome.vertx;

//import java.util.Set;
//import io.vertx.core.http.HttpMethod;
//import io.vertx.ext.web.handler.CorsHandler;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.FileSystemAccess;
import io.vertx.ext.web.handler.StaticHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * Vert.x Verticle实现，用于启动和管理HTTP服务器。 Vert.x Verticle implementation for starting
 * and managing an HTTP server. 处理路由、静态文件服务和HttpAction映射。 Handles routing,
 * static file serving, and HttpAction mappings.
 */
@Slf4j
public class VerticleEngine extends AbstractVerticle {

	// 常量定义 / Constant definitions
	private static final int KB = 1024;
	private static final int MB = 1024 * KB;

	// 默认缓冲区大小（2KB），优化网络性能
	// Default buffer size (2KB), optimized for network performance
	private static final int DEFAULT_BUFFER_SIZE = 2 * KB;

	// 默认空闲超时时间（90秒），避免长时间无活动连接
	// Default idle timeout (90 seconds), prevents long inactive connections
	private static final int DEFAULT_IDLE_TIME = 90;

	// 默认最大请求体大小（50MB），防止过大请求
	// Default max body size (50MB), prevents oversized requests
	private static final int DEFAULT_BODY_LIMIT = 50 * MB;

	// 默认最大WebSocket帧大小（1MB），支持较大消息
	// Default max WebSocket frame size (1MB), supports larger messages
	private static final int DEFAULT_MAX_WEBSOCKET_FRAME_SIZE = 1_000_000;

	/**
	 * 默认构造函数。 Default constructor.
	 */
	public VerticleEngine() {
		// 无需额外初始化 / No additional initialization needed
	}

	/**
	 * 启动Verticle，配置并运行HTTP服务器。 Starts the Verticle, configures and runs the HTTP
	 * server.
	 * 
	 * @param startFuture 用于通知Vert.x启动结果 / Promise to notify Vert.x of startup
	 *                    result
	 * @throws Exception 如果启动失败 / If startup fails
	 */
	@Override
	public void start(Promise<Void> startFuture) throws Exception {
		// 配置HTTP服务器选项
		// Configure HTTP server options
		HttpServerOptions options = new HttpServerOptions().setMaxWebSocketFrameSize(DEFAULT_MAX_WEBSOCKET_FRAME_SIZE) // 设置WebSocket帧大小
																														// /
																														// Set
																														// WebSocket
																														// frame
																														// size
				.setTcpKeepAlive(true) // 启用TCP保活 / Enable TCP keep-alive
				.setIdleTimeout(DEFAULT_IDLE_TIME) // 设置空闲超时 / Set idle timeout
				.setAcceptBacklog(10) // 设置接收队列大小 / Set accept backlog
				.setReceiveBufferSize(DEFAULT_BUFFER_SIZE) // 设置接收缓冲区 / Set receive buffer size
				.setSendBufferSize(DEFAULT_BUFFER_SIZE) // 设置发送缓冲区 / Set send buffer size
				.setTcpNoDelay(true) // 禁用Nagle算法，优化延迟 / Disable Nagle's algorithm, optimize latency
				.setReuseAddress(true) // 允许端口重用 / Allow port reuse
				.setSoLinger(0) // 立即关闭连接 / Close connection immediately
				.setLogActivity(true); // 启用活动日志 / Enable activity logging

		// 创建HTTP服务器和路由器
		// Create HTTP server and router
		HttpServer server = vertx.createHttpServer(options);
		Router router = Router.router(vertx);
//		router.route()
//				.handler(CorsHandler.create().addOrigin("*")
//						.allowedMethods(Set.of(HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS))
//						.allowedHeaders(Set.of("Content-Type", "access_token")));
		// 添加BodyHandler，限制请求体大小
		// Add BodyHandler with body size limit
		router.route().handler(BodyHandler.create().setBodyLimit(DEFAULT_BODY_LIMIT));

		// 注册HttpAction路由
		// Register HttpAction routes
		StartVertx.ins.getActions().forEach((path, action) -> {
			String uri = path.split("_")[0];
			router.route(uri).handler(action::initHandle);
			log.debug("注册路由 / Registered route: {}", uri);
		});

		// 配置静态文件服务
		// Configure static file serving
		String webRoot = System.getProperty("user.dir") + "/webroot";
		StaticHandler staticHandler = StaticHandler.create(FileSystemAccess.ROOT, webRoot).setCachingEnabled(true); // 启用缓存，提升性能
																													// /
																													// Enable
																													// caching
																													// for
																													// performance
		router.route("/*").handler(staticHandler); // 所有未匹配路径处理静态文件 / Handle all unmatched paths with static files

		// 启动服务器并监听端口
		// Start server and listen on port
		server.requestHandler(router).listen(StartVertx.ins.getPort(), res -> {
			if (res.succeeded()) {
//				log.info(">> 启动Web服务于端口 / Start web service on port: {}", res.result().actualPort());
				startFuture.complete();
			} else {
//				log.error(">> 启动失败 / Start failed: {}", res.cause().getMessage(), res.cause());
				startFuture.fail(res.cause());
			}
		});
	}

	/**
	 * 停止Verticle，清理资源。 Stops the Verticle, cleans up resources.
	 * 
	 * @throws Exception 如果停止失败 / If stopping fails
	 */
	@Override
	public void stop() throws Exception {
		log.info(">> 停止Verticle / Stopping Verticle");
		// 当前无需额外清理 / No additional cleanup needed currently
	}
}